<?php
namespace nimo\domains\car_balance\controllers;

use App;
use BaseController;
use Sentry;
use Session;
use View;
use Input;
use Request;
use Redirect;
use Validator;
use nimo\domains\car_balance\Model\Parts;
use nimo\domains\car_balance\Model\Customer;
use nimo\domains\car_balance\Model\CarAuction;

class PartsController extends BaseController
{
    /**
     * Declare the rules for the form validation
     *
     * @var array
     */
    protected $validationRules = array(
            "purchase_date"              => "required|date",
            "car_auction_id"             => "required|integer",
            "parts_name"                 => "required|max:40",
            "seller"                     => "required|max:40",
            "seller_send_type"           => "required|max:40",
            "recieve_date"               => "required|date",
            "pickup_car_chassis_number"  => "required|max:40",
            "payment_type"               => "required|integer",
            "payment_commission"         => "required|integer",
            "payment_date"               => "required|date",
            "price"                      => "required|integer",
            "delivery_fee"               => "required|integer",
            "commission"                 => "required|integer",
            "customer_id"                => "required|integer",
            "fee_mongol"                 => "required|integer",
            "comment"                    => "required|max:1000",
            "cancel_flag"                => "integer",
    );

    /**
     * Validation rules for Parts create
     *
     * @var array
     */
    protected $validationRules1 = array(
            "purchase_date"              => "required|date",
            "auction_id"                 => "required",
            "parts_name"                 => "required",
            "seller"                     => "required",
            "seller_send_type"           => "max:40",
            "pickup_car_chassis_number"  => "max:40",
            //"customer_id"                => "required|integer",
            "comment"                    => "max:1000",
    );

    /**
     * Declare the rules for the form validation
     *
     * @var array
     */
    protected $validationRules2 = array(
        "payment_type"               => "max:255",
        "payment_commission"         => "integer",
        "payment_date"               => "date",
        "price"                      => "integer",
        "delivery_fee"               => "integer",
        "commission"                 => "integer",
        "fee_mongol"                 => "integer",
        "comment"                    => "max:1000",
    );

    /**
    * Show a list of all the parts.
    *
    * @return View
    */
    public function getIndex()
    {
        if(Request::has('reset')) {
            Session::forget('parts_list.filter');
        }
        // Grab all the parts
        $query = new Parts();
        $lastMonths = array(date("Y-m-01",strtotime("-3 month")),date("Y-m-t"));

        if(Request::isMethod('POST')) {
            // Filter form values to session
            $purchase_date = is_null(Input::get('purchase_date')) ? $lastMonths : explode(' - ',Input::get('purchase_date'));
            Session::put('parts_list.filter.purchase_date', $purchase_date);
            $customer_id = is_null(Input::get('customer_id')) ? '0' : Input::get('customer_id');
            Session::put('parts_list.filter.customer_id', $customer_id);
            $auction_id = is_null(Input::get('auction_id')) ? '0' : Input::get('auction_id');
            Session::put('parts_list.filter.auction_id', $auction_id);
            $cancelled = is_null(Input::get('cancelled')) ? false : Input::get('cancelled');
            Session::put('parts_list.filter.cancelled', $cancelled);
            $deleted = is_null(Input::get('deleted')) ? false : Input::get('deleted');
            Session::put('parts_list.filter.deleted', $deleted);
        } else {
            // Filter values from session
            $purchase_date = Session::get('parts_list.filter.purchase_date', $lastMonths);
            $customer_id = Session::get('parts_list.filter.customer_id', '0');
            $auction_id = Session::get('parts_list.filter.auction_id', '');
            $cancelled = Session::get('parts_list.filter.cancelled', false);
            $deleted = Session::get('parts_list.filter.deleted', false);
        }

        // only for customer
        if(Sentry::getUser()->hasAccess('customer', false)) {
            // user table-s customer-g herhen tanih we?
            $user = Sentry::getUser();
            $customerQuery = new Customer();
            $customer = $customerQuery->where('id', '=', $user->customer_id)->first();
            if($customer) {
                $customer_id = $customer->id;
                Session::put('parts_list.filter.customer_id', $customer_id);
            } else {
                App::abort(403, 'Хандах эрх хүрэлцэхгүй байна!');
            }
        }

        // Applying filters
        if(count($purchase_date) >1 )
            $query = $query->whereBetween('purchase_date', array(date('Ymd', strtotime($purchase_date[0])),date('Ymd', strtotime($purchase_date[1]))));
        if($customer_id != '0') {
            $query = $query->where('customer_id', '=', $customer_id);
        }
        if($auction_id != 0)
            $query = $query->where('auction_id', '=', $auction_id);
        if($cancelled)
            $query = $query->whereNotNull('cancel_flag')->where('cancel_flag', '<>', '');
        if($deleted)
            $query = $query->withTrashed();

        // QUERY ORDER
        $query = $query->orderBy('purchase_date', 'desc');

        $query = $query->with('customer');

        $filters = array(
            'purchase_date' => $purchase_date,
            'customer_id' => $customer_id,
            'auction_id' => $auction_id,
            'cancelled' => $cancelled,
            'deleted' => $deleted,
        );
        
        // Page Array
        $perpage = Request::has('perpage') ? Request::get('perpage') : 20;
        $page = Request::has('page') ? Request::get('page') : 1;
        $total_page = ($query->count() / $perpage) + (($query->count() % $perpage > 0)? 1: 0);
        $pagination = array('total_page' => $total_page, 'perpage' => $perpage, 'page' => $page);

        // Paginate the parts
        $parts = $query->paginate($perpage);

        // Show the page
        return View::make('nimo.domains.car_balance.Main.parts_list', compact('parts', 'filters', 'pagination'))
            ->with('customer_list', array_merge(array('0' => 'All Customer'), Customer::lists('name', 'id')))
            ->with('customer', isset($customer) ? $customer : null)
        ;
    }

    /**
     * Parts create.
     *
     * @return View
     */
    public function getCreate()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Show the page
        return View::make('nimo.domains.car_balance.Main.part_create')
            ->with('customer_list', array_merge(array(''),Customer::lists('name', 'id')))
            ;
    }

    /**
     * Parts create form processing.
     *
     * @return Redirect
     */
    public function postCreate()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRules1);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }


        // Create a new parts
        $parts = new Parts();

        // Update the parts data
        $parts->purchase_date              = e(Input::get('purchase_date'));
        $parts->auction_id                 = e(Input::get('auction_id'));
        $parts->parts_name                 = e(Input::get('parts_name'));
        $parts->seller                     = e(Input::get('seller'));
        $parts->seller_send_type           = e(Input::get('seller_send_type'));
        $parts->recieve_date               = e(Input::get('recieve_date'));
        $parts->pickup_car_chassis_number  = e(Input::get('pickup_car_chassis_number'));
        $parts->payment_type               = e(Input::get('payment_type'));
        $parts->payment_commission         = e(Input::get('payment_commission'));
        $parts->payment_date               = e(Input::get('payment_date'));
        $parts->price                      = e(Input::get('price'));
        $parts->delivery_fee               = e(Input::get('delivery_fee'));
        $parts->commission                 = e(Input::get('commission'));
        $parts->customer_id                = e(Input::get('customer_id'));
        $parts->fee_mongol                 = e(Input::get('fee_mongol'));
        $parts->comment                    = e(Input::get('comment'));
        $parts->cancel_flag                = e(Input::get('cancel_flag'));

        // Was the parts created?
        if($parts->save())
        {
            // Redirect to the new parts page
            return Redirect::route('car_balance.parts.index')->with('success', 'Parts created successfully');
        }

        // Redirect to the parts create page
        return Redirect::route('car_balance.parts.create')->with('error', 'Parts was not created, please try again.');
    }

    /**
     * Parts update.
     *
     * @param  int  $id
     * @return View
     */
    public function getEdit($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the parts exists
        if (is_null($part = Parts::find($id)))
        {
            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('error', "Parts [$id] does not exist.");
        }

        // Show the page
        return View::make('nimo.domains.car_balance.Main.part_expense', compact('part'))
        ;
    }

    /**
     * Parts update form processing page.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function postEdit($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the parts exists
        if (is_null($parts = Parts::find($id)))
        {
            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('error', "Parts [$id] does not exist.");
        }

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRules2);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        // Update the parts data
        $parts->payment_type               = e(Input::get('payment_type'));
        $parts->payment_commission         = e(Input::get('payment_commission'));
        $parts->payment_date               = e(Input::get('payment_date'));
        $parts->price                      = e(Input::get('price'));
        $parts->delivery_fee               = e(Input::get('delivery_fee'));
        $parts->commission                 = e(Input::get('commission'));
        $parts->fee_mongol                 = e(Input::get('fee_mongol'));
        $parts->comment                    = e(Input::get('comment'));

        // Was the parts updated?
        if($parts->save())
        {
            // Redirect to the Parts page
            return Redirect::route('car_balance.parts.index')->with('success', 'Parts updated successfully.');
        }

        // Redirect to the Parts management page
        return Redirect::route('car_balance.parts.edit', array('id' => $id))->with('error', 'Parts was not updated, please try again');
    }

    /**
     * Parts show.
     *
     * @param  int  $id
     * @return View
     */
    public function getShow($id = null)
    {
        // Check if the parts exists
        if (is_null($parts = Parts::find($id)))
        {
            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('error', "Parts [$id] does not exist.");
        }

        // only for customer
        if(Sentry::getUser()->hasAccess('customer', false)) {
            // user table-s customer-g herhen tanih we?
            $user = Sentry::getUser();
            $customerQuery = new Customer();
            $customer = $customerQuery->where('id', '=', $user->customer_id)->first();
            if($customer) {
                if($parts->customer_id != $customer->id)
                    App::abort(403, 'Хандах эрх хүрэлцэхгүй байна!');
            } else {
                App::abort(403, 'Хандах эрх хүрэлцэхгүй байна!');
            }
        }

        // Show the page
        return View::make('nimo.domains.car_balance.Main.part_show', compact('parts'));
    }

    /**
     * Delete the given parts.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function getDelete($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the parts exists
        if (is_null($parts = Parts::find($id)))
        {
            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('error', 'There was an issue deleting the Parts. Please try again.');
        }

        
        // Delete the parts
        $parts->delete();

        // Redirect to the Parts list page
        return Redirect::route("car_balance.parts.index")->with('success', 'Parts was successfully deleted.');
    }

    /**
     * Cancel the given parts.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function getCancel($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the parts exists
        if (is_null($parts = Parts::find($id)))
        {
            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('error', 'There was an issue cancelling the Parts. Please try again.');
        }


        // Delete the parts
        $parts->cancel_flag = date('Ymd');
        $parts->save();

        // Redirect to the Parts list page
        return Redirect::route("car_balance.parts.index")->with('success', 'Parts was successfully cancelled.');
    }

    /**
     * Un Cancel the given parts.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function getUnCancel($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the parts exists
        if (is_null($parts = Parts::find($id)))
        {
            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('error', 'There was an issue undo cancelling the Parts. Please try again.');
        }


        // Delete the parts
        $parts->cancel_flag = null;
        $parts->save();

        // Redirect to the Parts list page
        return Redirect::route("car_balance.parts.index")->with('success', 'Parts was successfully undo cancelled.');
    }

    /**
    * Restore a deleted parts.
    *
    * @param  int  $id
    * @return Redirect
    */
    public function getRestore($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        try
        {
            // Get parts information
            $parts = Parts::withTrashed()->find($id);

            // Restore the parts
            $parts->restore();

            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('success', 'Parts was successfully restored.');
        }
        catch (NotFoundException $e)
        {
            // Redirect to the Parts management page
            return Redirect::route('car_balance.parts.index')->with('error', "Parts [$id] does not exist.");
        }
    }
}